<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('表对象信息详情')" />
    <th:block th:include="include :: datetimepicker-css" />
    <link th:href="@{/css/table_update.css}" rel="stylesheet"/>
</head>
<body class="white-bg">
<div class="container-div">
    <div class="title">[[${tableName}]]</div>
    <input type="hidden" name="tableEnName" th:value="${tableEnName}">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox-content">
                <form class="form-horizontal" id="fieldForm">
                </form>
            </div>
        </div>
        <div class="footer-btn">
            <a class="btn btn-success btn-rounded btn-sm" onclick="saveInfo()">保存</a>
            <a class="btn btn-warning btn-rounded btn-sm reset">重置</a>
        </div>
    </div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />
<script id="fieldTpl" type="text/template">
    {{# layui.each(d.data, function(index, a){ }}
        {{# if(!(a.fieldtype=='1' && !d.fieldData[a.mysqlfieldname])) { }}
        <div class="form-group col-sm-4">
            <label class="col-sm-4 control-label" >{{a.fieldname}}：</label>
            <div class="col-sm-8">
                {{# if(a.isfieldenum=='Y') { }}
                    <select name="{{a.mysqlfieldname}}" data-id={{a.id}}  data-value="{{d.fieldData[a.mysqlfieldname]||''}}"
                            class="form-control field-enum {{# if(a.fieldtype=='2') { }}choose-more{{#}}}" >
                    </select>
                {{#} else { }}
                    {{# if(a.mysqlfielddatatype.indexOf("datetime")>=0) { }}
                        <div class="input-group date">
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                            <input type="text" class="form-control" name="{{a.mysqlfieldname}}"  id="datetimepicker-{{a.id}}"
                                   placeholder="yyyy-MM-dd HH:mm:ss" value="{{d.fieldData[a.mysqlfieldname]||''}}" >
                        </div>
                    {{#} else { }}
                        <input name="{{a.mysqlfieldname}}" data-id={{a.id}} class="form-control {{# if(a.fieldtype=='2') { }}choose-more {{#}}}"
                               type="text" value="{{d.fieldData[a.mysqlfieldname]||''}}"
                               {{# if(a.fieldtype=='1' || a.fieldtype=='2') { }}readOnly{{#}}}>
                    {{#}}}
                {{#}}}
                {{# if(a.fieldtype=='2') { }}<a class="fieldChoose" data-id={{a.id}} style="margin-left: 20px;">选择</a>{{#}}}
            </div>
        </div>
    {{#}}}
    {{# }); }}
</script>
<script id="fieldEnumTpl" type="text/template">
    {{# if(storageData) { }}
    <option value="">请选择</option>
    {{#}}}
    {{# layui.each(d.data, function(index, a){ }}
    <option value="{{a.dictValue}}" {{#if(a.dictValue==d.selectData){}}selected{{# }}}>{{a.dictLabel}}</option>
    {{# }); }}
</script>
<script th:inline="javascript">
    // 获取字段
    var prefix = ctx + "table/table";
    var prefix1 = "http://code.suzhi.link:8070";
    // var prefix1 = "http://127.0.0.1:9099";
    var tableId = [[${tableId}]];
    var index = [[${index}]];
    var storageData = sessionStorage.getItem("tableInfo"+"_"+tableId+"_"+index);
    $(function () {
        fieldInfoList()
        $(".reset").click(function () {
            window.location.reload()
        })
        $("body").on("click",".fieldChoose",function () {
            var id = $(this).data("id");
            var options = {
                title: '字段数据选择',
                height: "600",
                url: prefix + "/tableFieldChoose/" + id,
                btn: ['确定', '取消'],
                callBack: function (index, layero) {
                    var iframeWin = layero.find('iframe')[0];
                    iframeWin.contentWindow.submitHandler(index, layero);
                    return false;
                }
            };
            $.modal.openOptions(options);
        })
    })
    // 获取字段详情
    function fieldInfoList() {
        // 页面大图
        let config = {
            url: prefix1 + "/tFieldInfo/queryFiledInfo",
            type: "post",
            dataType: "json",
            contentType:"application/json",
            async:false,
            data: JSON.stringify({
                "tableId": tableId
            }),
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function (result) {
                $.modal.closeLoading();
                if (result.errCode == 1) {
                    var fieldTplHtml = $("#fieldTpl").html();
                    result.fieldData = storageData ? JSON.parse(decodeURIComponent(storageData)):{}
                    result.data.forEach(function (e) {
                        if(e.mysqlfielddatatype.indexOf("datetime")>=0 && result.fieldData[e.mysqlfieldname]){
                            result.fieldData[e.mysqlfieldname] = new Date(result.fieldData[e.mysqlfieldname]).format("yyyy-MM-dd hh:mm:ss")
                        }
                    })
                    laytpl(fieldTplHtml).render(result, function (html) {
                        $("#fieldForm").empty();
                        $("#fieldForm").append(html);
                    });
                    result.data.forEach(function (e) {
                        e.mysqlfielddatatype.indexOf("datetime")>=0 && $("#datetimepicker-"+e.id).datetimepicker({
                            format: "yyyy-mm-dd hh:ii:ss",
                            autoclose: true
                        });
                    })
                    $(".field-enum").each((e,dom)=>{
                        queryFiledEnum($(dom).data());
                    });
                    return false;
                }
                if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.message)
                    return false;
                }
                $.modal.alertError(result.message);
            }
        };
        $.ajax(config);
    }
    // 根据字段获取枚举值
    function queryFiledEnum(obj) {
        // 页面大图
        let config = {
            url: prefix1 + "/tFieldInfo/queryFiledEnum",
            type: "post",
            dataType: "json",
            contentType:"application/json",
            async:false,
            data: JSON.stringify({
                "tableId": obj.id
            }),
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function (result) {
                $.modal.closeLoading();
                if (result.errCode == 1) {
                    var fieldTplHtml = $("#fieldEnumTpl").html();
                    result.selectData = obj.value
                    laytpl(fieldTplHtml).render(result, function (html) {
                        $(".field-enum[data-id='"+obj.id+"']").empty();
                        $(".field-enum[data-id='"+obj.id+"']").append(html)
                    });
                    return false;
                }
                if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.message)
                    return false;
                }
                $.modal.alertError(result.message);
            }
        };
        $.ajax(config);
    }
    $.fn.serializeObjectNoNull = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [ o[this.name] ];
                }
                o[this.name].push(this.value);
            } else {
                o[this.name] = this.value;
            }
        });
        return o;
    };
    function saveInfo() {
        // 新增
        if(!storageData){
            addRow();
            return false;
        }
        // 更新
        let config = {
            url: prefix1 + "/dataManager/updateMockData",
            type: "post",
            dataType: "json",
            contentType:"application/json",
            async:false,
            data: JSON.stringify({
                tableId: tableId,
                tableName:$("input[name='tableEnName']").val(),
                data:$("#fieldForm").serializeObjectNoNull()
            }),
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function (result) {
                $.modal.closeLoading();
                if (result.errCode == 1) {
                    if (typeof callback == "function") {
                        callback(result);
                    }
                    $.operate.successTabCallback(result);
                    return false;
                }
                if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.message)
                    return false;
                }
                $.modal.alertError(result.message);
            }
        };
        $.ajax(config);
    }
    //新增行
    function addRow(){
        var serializeObject = $("#fieldForm").serializeObject();
        var values = [];
        Object.keys(serializeObject).forEach(function (e) {
            let obj = {};
            obj['fieldName'] = e;
            obj['value'] = serializeObject[e];
            values.push(obj);
        });
        console.log(values);
        let config = {
            url: prefix1 + "/dataManager/createBusinessData",
            type: "post",
            dataType: "json",
            contentType:"application/json",
            async:false,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            data: JSON.stringify({
                tableName:$("input[name='tableEnName']").val(),
                values: values,
            }),
            success: function (result) {
                $.modal.closeLoading();
                if (result.errCode == 1) {
                    if (typeof callback == "function") {
                        callback(result);
                    }
                    $.operate.successTabCallback(result);
                    return false;
                }
                if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.message)
                    return false;
                }
                $.modal.alertError(result.message);
            }
        }
        $.ajax(config);
    }
    // 更新数据通过选择方式
    function updateDataByChoose(id,value){
        $("input[data-id='"+id+"']").val(value);
    }
</script>
</body>
</html>